import _, { times } from "lodash"


//防抖： 调用函数一段事件后才会执行--多次调用将会重新计时，可以用来做搜索文字提示等功能
let fandou = _.debounce(()=>{
    console.log("debounce");
},1000);


//节流： 一定时间内只能调用函数一次，就像枪的开火次数，可以用来限制用户向后端发起请求的次数
let jieliu = _.throttle(()=>{
    console.log("throttle");
},1000);


let btns = document.getElementsByClassName("button");
btns[0].addEventListener('click',fandou);
btns[1].addEventListener('click',jieliu);



function debounce(fn,delay) {
    if(typeof fn !== 'function') {
        throw "fn must be a function";
    }
    let id = 0;
    return function() {
        if(id) {
            clearTimeout(id);
            id = 0;
        }
        id = setTimeout(fn,delay);
    }
}

function throttle(fn,delay) {
    if(typeof fn !== 'function') {
        throw "fn must be a function";
    }
    let pre = 0;
    return function() {
        if(Date.now() - pre >delay) {
            fn();
            pre = Date.now();
        }
    }
}

let mdebounce = debounce(()=>{
    console.log("我的防抖");
},1000);
let mthrottle = throttle(()=>{
    console.log("我的节流");
},1000);

btns = document.getElementsByClassName('mbutton');
btns[0].addEventListener("click",mdebounce);
btns[1].addEventListener("click",mthrottle);



